import { defineStore } from 'pinia'
import request from '@/utils/request'

export const useUserStore = defineStore('user', {
  state: () => ({
    userList: [],
    currentUser: null,
    loading: false
  }),
  actions: {
    async fetchUserList(params = {}) {
      this.loading = true
      try {
        // 支持分页和模糊搜索
        const query = {}
        if (params.page && params.pageSize) {
          query._page = params.page
          query._limit = params.pageSize
        }
        if (params.keyword) {
          query.q = params.keyword
        }
        const res = await request.get('/users', { params: query, fullResponse: true })
        this.userList = res.data
        return {
          data: res.data,
          total: parseInt(res.headers['x-total-count'] || res.data.length || 0)
        }
      } catch (error) {
        console.error('获取用户列表失败', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    async addUser(user) {
      try {
        // 保证不传id字段
        const payload = { ...user }
        delete payload.id
        if (!payload.roleId) payload.roleId = 2 // 默认普通员工
        if (!payload.password) payload.password = '123456'
        const res = await request.post('/users', payload)
        return res
      } catch (error) {
        console.error('添加用户失败', error)
        throw error
      }
    },
    async updateUser(user) {
      try {
        const res = await request.put(`/users/${user.id}`, user)
        const index = this.userList.findIndex(item => item.id === user.id)
        if (index !== -1) {
          this.userList.splice(index, 1, res.data)
        }
        return res
      } catch (error) {
        console.error('更新用户失败', error)
        throw error
      }
    },
    async deleteUser(id) {
      try {
        await request.delete(`/users/${id}`)
        this.userList = this.userList.filter(item => item.id !== id)
      } catch (error) {
        console.error('删除用户失败', error)
        throw error
      }
    }
  }
})  